package top.kaoshanji.p2ch15b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 代码清单-p2ch15b-457页c：等待结束的主类
 * 主线程等待子线程执行结束
 * author kaoshanji
 * ^_^
 * create time 2025/2/24 17:27
 */
public class MyLatchDemo {

    private static final Logger logger = LogManager.getLogger(MyLatchDemo.class);

    public static void main(String[] args) throws InterruptedException {
        logger.info("...start...");

        int workerNum = 10;
        // 协作的共享变量：主线程（阻塞）、多个子线程
        MyLatch latch = new MyLatch(workerNum);

        MyLatchWorkerThread[] workerThreads = new MyLatchWorkerThread[workerNum];
        for (int i = 0; i < workerNum; i++) {
            workerThreads[i] = new MyLatchWorkerThread(latch); // 共享的对象通过构造器传入
            workerThreads[i].start(); // 将共享数字减 1
        }


        latch.await(); // 主线程等待结束，条件是已经没有未执行的线程了

        System.out.println("collect worker results");

        logger.info("...end...");
    }

}
